/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * GUIClient.java
 *
 * Created on Apr 22, 2011, 3:11:29 PM
 */

package mbox.client;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.table.*;
import java.io.*;
import java.util.*;
import mbox.helper.Utilities;
/**
 *
 * @author User
 */
public class GUIClient extends javax.swing.JFrame {

    /** Creates new form GUIClient */
    public GUIClient() {
        initComponents();
        client = new Client(model);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        user_field = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        addir_button = new javax.swing.JButton();
        connect_button = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        model = new DefaultTableModel(new Object [][] {},
            new String [] {
                "Name", "Path"
            });
            RepoTable = new javax.swing.JTable();
            del_button = new javax.swing.JButton();
            sync_button = new javax.swing.JButton();
            newdir_field = new javax.swing.JTextField();
            jLabel4 = new javax.swing.JLabel();
            pass_field = new javax.swing.JPasswordField();

            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

            jLabel1.setText("username");

            jLabel2.setText("password");

            jLabel3.setText("Directories");

            addir_button.setText("Add Directory");
            addir_button.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseClicked(java.awt.event.MouseEvent evt) {
                    addir_buttonMouseClicked(evt);
                }
            });

            connect_button.setText("Connect");
            connect_button.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseClicked(java.awt.event.MouseEvent evt) {
                    connect_buttonMouseClicked(evt);
                }
            });

            RepoTable.setModel(model
            );
            TableColumn col = RepoTable.getColumnModel().getColumn(0);
            col.setPreferredWidth(130);
            col = RepoTable.getColumnModel().getColumn(1);
            col.setPreferredWidth(319);
            RepoTable.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
            RepoTable.setAutoscrolls(false);
            RepoTable.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
            RepoTable.setMinimumSize(new java.awt.Dimension(450, 0));
            RepoTable.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseClicked(java.awt.event.MouseEvent evt) {
                    RepoTableMouseClicked(evt);
                }
            });
            jScrollPane1.setViewportView(RepoTable);
            File f = new File("files.txt");
            if(f.exists()){
                try {
                    Scanner Sc = new Scanner(f);
                    while (Sc.hasNextLine()) {
                        String nm = Sc.nextLine();
                        String dr = Sc.nextLine();
                        model.addRow(new Object[]{nm, dr});
                    }
                    Sc.close();
                } catch (FileNotFoundException ex) {
                    Logger.getLogger(GUIClient.class.getName()).log(Level.SEVERE, null, ex);
                }
            }else{
                try {
                    f.createNewFile();
                } catch (IOException ex) {
                    Logger.getLogger(GUIClient.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

            del_button.setText("Delete");
            del_button.setEnabled(false);
            del_button.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseClicked(java.awt.event.MouseEvent evt) {
                    del_buttonMouseClicked(evt);
                }
            });

            sync_button.setText("Synchronize");
            sync_button.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseClicked(java.awt.event.MouseEvent evt) {
                    sync_buttonMouseClicked(evt);
                }
            });

            jLabel4.setText("LOGO");

            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jLabel4)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 159, Short.MAX_VALUE)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addComponent(jLabel2)
                                .addComponent(jLabel1))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(pass_field)
                                .addComponent(user_field, javax.swing.GroupLayout.DEFAULT_SIZE, 135, Short.MAX_VALUE))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(connect_button))
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                            .addComponent(newdir_field, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(addir_button)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 62, Short.MAX_VALUE)
                            .addComponent(sync_button, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(del_button, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(layout.createSequentialGroup()
                            .addGap(10, 10, 10)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 452, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addContainerGap())
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(2, 2, 2)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(user_field, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jLabel1))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(jLabel2)
                                    .addComponent(pass_field, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(1, 1, 1))
                            .addComponent(connect_button, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addComponent(jLabel4))
                    .addGap(26, 26, 26)
                    .addComponent(jLabel3)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(1, 1, 1)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(addir_button)
                        .addComponent(newdir_field, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(del_button, javax.swing.GroupLayout.DEFAULT_SIZE, 35, Short.MAX_VALUE)
                        .addComponent(sync_button, javax.swing.GroupLayout.DEFAULT_SIZE, 35, Short.MAX_VALUE))
                    .addContainerGap())
            );

            pack();
        }// </editor-fold>//GEN-END:initComponents

    private void connect_buttonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_connect_buttonMouseClicked

        if(connect_button.getText().equals("Connect")){
             if(client.loginSuccess(user_field.getText(),pass_field.getText())){
                
                connect_button.setText("Disconnect");

                synchroThread.start();
                SynAvailable = true;
            } else {
                JOptionPane.showMessageDialog(this, "Login Failed, Make Sure Your Username and Password is Correct and Your Computer is Connected to Internet");
            }

        }else{
            if(client.logoutSuccess(user_field.getText(),pass_field.getPassword().toString())){
                
                SynAvailable = false;
                connect_button.setText("Connect");
            } else {
                JOptionPane.showMessageDialog(this, "Logout Failed");
            }
            
        }

    }//GEN-LAST:event_connect_buttonMouseClicked

    private void RepoTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_RepoTableMouseClicked
        if(RepoTable.isEnabled())del_button.setEnabled(true);
    }//GEN-LAST:event_RepoTableMouseClicked

    private void sync_buttonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_sync_buttonMouseClicked

        client.doSynchronize();
    }//GEN-LAST:event_sync_buttonMouseClicked

    private void addir_buttonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_addir_buttonMouseClicked

        String nd = newdir_field.getText();
        if(nd.isEmpty())
            JOptionPane.showMessageDialog(this, "Insert The New Name First!!");
        else {
            int n = model.getRowCount();
            boolean exist = false;
            while(n>0){
                
                if(nd.equals(model.getValueAt(n-1, 0))) exist=true;
                --n;
            }
            if(!exist){

                JFileChooser chooser = new JFileChooser();
                chooser.setCurrentDirectory(new java.io.File("."));
                chooser.setDialogTitle("Select A Directory");
                chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                //
                // disable the "All files" option.
                //
                chooser.setAcceptAllFileFilterUsed(false);
                //
                if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION && chooser.getSelectedFile().isDirectory()) {
                     model.addRow(new Object[]{nd,chooser.getSelectedFile()});
                     updateFiles();
                  }
                else {
                  System.out.println("No Selection ");
                  }

            }else
                JOptionPane.showMessageDialog(this, "The Name Is Already Exist");

        }

    }//GEN-LAST:event_addir_buttonMouseClicked

    private void del_buttonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_del_buttonMouseClicked
        if(del_button.isEnabled() && RepoTable.getSelectedRow()>-1){
            model.removeRow(RepoTable.getSelectedRow());
            updateFiles();
        }
    }//GEN-LAST:event_del_buttonMouseClicked


    void updateFiles(){
        //Update files.txt
        File f = new File("files.txt");
        if(f.exists()){
                try {
                    PrintWriter Pw = new PrintWriter(f);
                    for(int i=0; i<RepoTable.getRowCount();++i){
                        Pw.println(model.getValueAt(i, 0));
                        Pw.println(model.getValueAt(i, 1));
                    }
                    Pw.close();
                } catch (FileNotFoundException ex) {
                    Logger.getLogger(GUIClient.class.getName()).log(Level.SEVERE, null, ex);
                }
        }else{
                try {
                    f.createNewFile();
                } catch (IOException ex) {
                    Logger.getLogger(GUIClient.class.getName()).log(Level.SEVERE, null, ex);
                }
        }
    }

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new GUIClient().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTable RepoTable;
    private javax.swing.JButton addir_button;
    private javax.swing.JButton connect_button;
    private javax.swing.JButton del_button;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField newdir_field;
    private javax.swing.JPasswordField pass_field;
    private javax.swing.JButton sync_button;
    private javax.swing.JTextField user_field;
    // End of variables declaration//GEN-END:variables
    DefaultTableModel model;
    private Client client;

    Thread synchroThread = new Thread() {
        @Override
        public void run() {
            long lastSync = System.currentTimeMillis();
            while (SynAvailable) {
                if (System.currentTimeMillis() - lastSync > Utilities.SYNC_PERIOD) {
                    client.doSynchronize();
                    lastSync = System.currentTimeMillis();
                }
            }
        }
    };

    boolean SynAvailable = false;

}
